package cn.itcast.jx.service.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import cn.itcast.jx.dao.BaseDao;
import cn.itcast.jx.domain.User;
import cn.itcast.jx.service.UserService;
import cn.itcast.jx.util.Encrypt;
import cn.itcast.jx.util.Page;
import cn.itcast.jx.util.PwdUtil;
import cn.itcast.jx.util.UtilFuns;

public class UserServiceImpl implements UserService {
	private BaseDao baseDao;

	
	private SimpleMailMessage  mailMessage;//邮件
	private JavaMailSenderImpl mailSender;	//邮件发送对象
	
	public void setMailMessage(SimpleMailMessage mailMessage) {
		this.mailMessage = mailMessage;
	}

	public void setMailSender(JavaMailSenderImpl mailSender) {
		this.mailSender = mailSender;
	}

	public void setBaseDao(BaseDao baseDao) {
		this.baseDao = baseDao;
	}

	@Override
	public List<User> find(String hql, Class<User> entityClass, Object[] params) {
		return baseDao.find(hql, entityClass, params);
	}

	@Override
	public Page<User> findPage(String hql, Page page, Class<User> entityClass,
			Object[] params) {
		return baseDao.findPage(hql, page, entityClass, params);
	}

	@Override
	public User get(Class<User> entityClass, Serializable id) {
		
		return baseDao.get(entityClass, id);
	}

	@Override
	public void saveOrUpdate(final User user) throws Exception {
		if(UtilFuns.isEmpty(user.getId())) {
			String id = UUID.randomUUID().toString();
			user.setId(id);
			user.getUserInfo().setId(id);
			final String password = PwdUtil.getPwd();
			user.setPassword(Encrypt.md5(password, user.getUserName()));
			
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					mailMessage.setTo(user.getEmail());
					mailMessage.setSubject("欢迎注册世纪佳缘");
					mailMessage.setText("您的注册账号为：" + user.getUserName() + "。登录密码为：" + password);
					mailSender.send(mailMessage);
				}
			}).start();
			
			
			baseDao.saveOrUpdate(user);
		}else {
			User user2 = baseDao.get(User.class, user.getId());
			user2.setDept(user.getDept());
			user2.setUserName(user.getUserName());
			user2.setState(user.getState());
			
			user2.getUserInfo().setName(user.getUserInfo().getName());
			user2.getUserInfo().setSalary(user.getUserInfo().getSalary());
			user2.getUserInfo().setGender(user.getUserInfo().getGender());
			user2.getUserInfo().setStation(user.getUserInfo().getStation());
			user2.getUserInfo().setTelephone(user.getUserInfo().getTelephone());
			user2.getUserInfo().setDegree(user.getUserInfo().getDegree());
			user2.getUserInfo().setRemark(user.getUserInfo().getRemark());
			user2.getUserInfo().setOrderNo(user.getUserInfo().getOrderNo());
			
			baseDao.saveOrUpdate(user2);
		}
		
	}

	@Override
	public void deleteById(Class<User> entityClass, Serializable id) {
		baseDao.deleteById(entityClass, id);
	}

	@Override
	public void delete(Class<User> entityClass, String[] ids) {
		for (String id : ids) {
			User user = baseDao.get(entityClass, id);
			user.setState(0);
			baseDao.saveOrUpdate(user);
		}
		
	}

	@Override
	public User findUserByName(String username) {
		List<User> list = baseDao.find("from User where userName = ?", User.class, new String[]{username});
		if(list!=null && list.size()>0){
			return list.get(0);
		}
		else {
			return null;
		}

	}

	@Override
	public void updateRole(User user) {
		
		baseDao.saveOrUpdate(user);
		
	}

	/*
	 * // 创建Properties 类用于记录邮箱的一些属性
	        final Properties props = new Properties();
	        // 表示SMTP发送邮件，必须进行身份验证
	        props.put("mail.smtp.auth", "true");
	        //此处填写SMTP服务器
	        props.put("mail.smtp.host", "smtp.qq.com");
	        //端口号，QQ邮箱给出了两个端口，但是另一个我一直使用不了，所以就给出这一个587
	        props.put("mail.smtp.port", "587");
	        // 此处填写你的账号
	        props.put("mail.user", "601506131@qq.com");
	        // 此处的密码就是前面说的16位STMP口令
	        props.put("mail.password", "viquayststeabbdg");
	        props.put("mail.debug", "true");

	        // 构建授权信息，用于进行SMTP进行身份验证
	        Authenticator authenticator = new Authenticator() {

	            protected PasswordAuthentication getPasswordAuthentication() {
	                // 用户名、密码
	                String userName = props.getProperty("mail.user");
	                String password = props.getProperty("mail.password");
	                return new PasswordAuthentication(userName, password);
	            }
	        };
	        // 使用环境属性和授权信息，创建邮件会话
	        Session mailSession = Session.getInstance(props, authenticator);
	        // 创建邮件消息
	        MimeMessage message = new MimeMessage(mailSession);
	        // 设置发件人
	        InternetAddress form = new InternetAddress(
	                props.getProperty("mail.user"));
	        message.setFrom(form);

	        // 设置收件人的邮箱1638064027@qq.com
	        InternetAddress to = new InternetAddress(user.getEmail());
	        message.setRecipient(RecipientType.TO, to);

	        // 设置邮件标题
	        message.setSubject("欢迎注册英雄联盟账号");

	        // 设置邮件的内容体
	        message.setContent("你好，欢迎您注册英雄联盟账号，您的登录名为：" + user.getUserName() + "。登录密码为：" + password + "。请牢记。", "text/html;charset=UTF-8");

	        // 最后当然就是发送邮件啦
	        Transport.send(message);
	 * 
	 */

}
